<template>
	<view class="uni-container">
		<!-- 媒体库弹窗 -->
		<uni-drawer class="insert-image-drawer" v-if="drawerWidth" ref="insertImageDrawer" mode="right"
			:width="drawerWidth">
			<uni-media-library mode="picker" :selected-count="1" :media-tabs="['image']"
				@onInsert="onInsertCover"></uni-media-library>
		</uni-drawer>
		<uni-forms ref="form" :model="formData" validateTrigger="bind">
			<uni-forms-item name="bannerfile" label="图片" required>
				<view style="display: flex;flex-direction: row;flex-wrap: wrap;">
					<view v-if="formData.bannerfile.length"
						style="position: relative;width: 300rpx;height: 300rpx;border: 1rpx solid #F0F0F0;border-radius: 20rpx;text-align: center;line-height: 300rpx;margin-right: 30rpx;margin-bottom: 30rpx;">
						<view
							style="position: absolute;right: 10rpx;top: 10rpx;z-index: 1;background: #6666667d;border-radius: 200rpx;width: 50rpx;height: 50rpx;line-height: 50rpx;"
							@click="() => removeThumbnail()">
							<uni-icons type="closeempty" size="16" color="#ffffff"></uni-icons>
						</view>
						<image style="width: 150px;height: 150px;position: absolute;top:0;left: 0;"
							:src="formData.bannerfile">
						</image>
					</view>
					<view v-if="formData.bannerfile == ''" @click="() => openInsertImageDrawer(0)"
						style="width: 300rpx;height: 300rpx;border: 1rpx solid #F0F0F0;border-radius: 20rpx;text-align: center;line-height: 300rpx;">
						<uni-icons class="placeholder" type="plusempty" size="60" color="#e8e8e8"></uni-icons>
					</view>
				</view>
				<!-- <uni-easyinput placeholder="图片文件信息，包括文件名、url等" v-model="formData.bannerfile"></uni-easyinput> -->
			</uni-forms-item>
			<uni-forms-item name="open_url" label="点击跳转">
				<uni-easyinput placeholder="点击跳转目标地址。如果是web地址则使用内置web-view打开；如果是本地页面则跳转本地页面；如果是schema地址则打开本地的app"
					v-model="formData.open_url" trim="both"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="sort" label="排序">
				<uni-easyinput placeholder="数字越小，排序越前" type="number" v-model="formData.sort"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="category_id" label="分类">
				<uni-easyinput placeholder="多个栏目的banner都存在一个表里时可用这个字段区分" v-model="formData.category_id"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="status" label="生效状态">
				<switch @change="binddata('status', $event.detail.value)" :checked="formData.status"></switch>
			</uni-forms-item>
			<uni-forms-item name="description" label="备注">
				<uni-easyinput placeholder="维护者自用描述" v-model="formData.description" trim="both"></uni-easyinput>
			</uni-forms-item>
			<view class="uni-button-group">
				<button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
				<navigator open-type="navigateBack" style="margin-left: 15px;">
					<button class="uni-button" style="width: 100px;">返回</button>
				</navigator>
			</view>
		</uni-forms>
	</view>
</template>

<script>
	import {
		validator
	} from '../../js_sdk/validator/opendb-banner.js';

	const db = uniCloud.database();
	const dbCmd = db.command;
	const dbCollectionName = 'opendb-banner';

	function getValidator(fields) {
		let result = {}
		for (let key in validator) {
			if (fields.includes(key)) {
				result[key] = validator[key]
			}
		}
		return result
	}



	export default {
		data() {
			let formData = {
				"bannerfile": "",
				"open_url": "",
				"sort": null,
				"category_id": "",
				"status": true,
				"description": ""
			}
			return {
				formData,
				formOptions: {},
				drawerWidth: 0,
				rules: {
					...getValidator(Object.keys(formData))
				}
			}
		},
		mounted() {
			const sysinfo = uni.getSystemInfoSync()
			this.drawerWidth = sysinfo.windowWidth * .8
		},
		onReady() {
			this.$refs.form.setRules(this.rules)
		},
		methods: {
			openInsertImageDrawer(e) {
				if (this.formData.bannerfile.length >= 1) {
					uni.showToast({
						title: '最多只能选择1张图片',
						icon: 'none',
						mask: true
					})
				} else {
					this.$refs.insertImageDrawer.open()
				}
			},
			async onInsertCover(selectMediaItems) {
				this.formData.bannerfile = selectMediaItems[0].src;
				this.$refs.insertImageDrawer.close()
			},
			removeThumbnail() {
				// 删除指定索引的图片
				this.formData.bannerfile = "";
				uni.showToast({
					title: '删除成功',
					icon: 'none'
				});
			},

			/**
			 * 验证表单并提交
			 */
			submit() {
				uni.showLoading({
					mask: true
				})
				this.$refs.form.validate().then((res) => {
					return this.submitForm(res)
				}).catch(() => {}).finally(() => {
					uni.hideLoading()
				})
			},

			/**
			 * 提交表单
			 */
			submitForm(value) {
				// 使用 clientDB 提交数据
				return db.collection(dbCollectionName).add(value).then((res) => {
					uni.showToast({
						title: '新增成功'
					})
					this.getOpenerEventChannel().emit('refreshData')
					setTimeout(() => uni.navigateBack(), 500)
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				})
			}
		}
	}
</script>